#!/bin/bash

SHELL=/bin/bash
PATH=/usr/bin:/bin:/usr/local/bin

#           h_track.sh
#  Thu Feb 18 13:18:39 2010
#  Copyright  2010  mk67
#  <rmk677@gmail.com>
#  GPL license v3

## Script colours Vars.
t='\e[0;39m'	#default terminal colour
r='\e[1;31m'	#red
v='\e[1;32m'	#green
y='\e[1;36m'	#cyan
j='\e[1;33m'	#yellow

########### CHANGE ME ###########
localuser=mike				# <<<
#cd /home/$USER
USER=$localuser
temp="/home/$USER"
cd /home/$USER
DIR="$temp/Documents/CLIM"	# <<<
#################################

# indispensable

#temp="/home/$USER/Dev"
#TR1="activite_en_cours.html"
TR1=".ACTIVE.1"
#TR1="$temp/Dev/svn/h_tracker/activite_en_cours.html"
#TR2="activite_en_cours.html.1"
TR2=".ACTIVE.2"
#tempfile
tempf="$temp/.tmp1"
tempfbak="$temp/.tmp2"
#TR2="$temp/Dev/svn/h_tracker/activite_en_cours.html.1"

log=$DIR/storm.log
#DIR="$temp/TEST/CLIM"
if [ -x /usr/bin/fcrontab ]; then
	preopts="&bootrun,mail(no)"
	if [[ $(whoami) != "root" ]];then
		timer="fcrontab"
	else
		timer="fcrontab -u $localuser"
	fi
	PRT1=2 #$[ 1+1 ]
	PRT2=3 #$[ 2+1 ]
	PRT8=9 #$[ 8+1 ]
	sep=","
else
	preopts=""
	timer="crontab"
	PRT1=1
	PRT2=2
	PRT8=8
	sep=","
fi
viewer="eog"
GUI=$(echo $0|sed -n 's/.*\///p')
TRAY="htrack_tray"
mkdir -p $DIR
# traduction
trad(){
storm="CYCLONE,HURRICANE"
none="PAS D'ALERTE EN COURS,CURRENTLY NO ALERT"
pre="$storm PRESENCE WARNING"
vigi="$storm VIGILANCE,$storm CLASS 3 ALERT"
orange="$storm ORANGE ALERT,$storm CLASS 4 ALERT"
red="$storm RED ALERT,$storm CLASS 5 ALERT"
report="BULLETIN,REPORT"
time="HEURE,HOUR"
day="JOUR,DAY"
}
messages(){
	CONNECTION="PAS DE CONNEXION, ABANDON." #,NO CONNECTION, ABORT."
	BULLETIN_CHECK="BULLETIN IDENTIQUE AU PRECEDENT." #,SAME REPORT AS PREVIOUS."
	ACTIVITY1="ACTIVITE EN COURS SUR LE BASSIN." #,ACTUAL AREA ACTIVITY."
	ACTIVITY2="AUCUNE ACTIVITE SUR LE BASSIN." #,NO ACTIVITY."
	ACTIVITY3="AUCUNE ACTIVITE EN COURS." #,NO ACTIVITY."
	INTERFACE="Démarrer l'interface ?" #,Start interface ?
	CR_DAILY_CK="Pas de contrôle journalier en cours." #,no active daily check."
	CR_BG_CK="paramétrage en tâche de fond." #,in background controls."
	CR_BULL="des bulletins" #,check control"
	CR_DO="s'effectue à" #,will be done"
	CR_HOUR="toutes les heures" #,each hours"
	CR_DAY="deux fois par jours" #,twice a day"
	CR_SAT_CK="Relevé des images satellites" #,Satellite images report"
	CR_SAT="des images satellites" #,"
	CR_SAT_NO_CK="Pas de contrôle d'activité en cours." #,"
	CR_SAT_EACH_S="s'effectue toutes les" #,will be done each"
	CR_SAT_EACH="s'effectue à" #,will be done"
	CR_SAT_NO="Relevé des images satellites désactivé." #,No satellite images report."
	CR_CK="Le relevé" #,reports"
	NO_ALERT="PAS D'ALERTE EN COURS" #,NO ACTIVE ALERT"
}
REUNION_TAGS(){
	query0='^BULLETIN'
	query1='^PRESSION'
	query2='^POSITION LE'
	query3='^DISTANCE'
	query4='^DEPLACEMENT'
	query5='/trkseg'
	query6=''
	query7=''
	query8='BULLETIN'
	query9='BULLETIN' #'IL.*PAS'
	query10='NATURE.*SYSTEME'
}
MIAMI_TAGS(){
	query0='^BULLETIN'
	query1='PRESSURE'
	query2='^LOCATION'
	query3='^ABOUT'
	query4='^MOVEMENT'
	query5='/trkseg'
	query6=''
	query7=''
	query8='DEPRESSION'
	query9='^NONE'
	query10='ADVISORY.*NUMBER'
}
DARWIN_TAGS(){
	query0='^BULLETIN'
	query1='PRESSURE'
	query2='^LOCATION'
	query3='^ABOUT'
	query4='^MOVEMENT'
	query5='/trkseg'
	query6=''
	query7=''
	query8='DEPRESSION'
	query9='^NONE'
	query10='ADVISORY.*NUMBER'
}
DARWIN(){
	cd $temp
	wget -q http://www.bom.gov.au/cgi-bin/wrap_fwo.pl
	IDA=$(cat wrap_fwo.pl|grep "ID[Q\|W]")
	mv -f $temp/wrap_fwo.pl $IDA ; cat $IDA > $temp/$ACTIVE.tmp
	cat $temp/$ACTIVE.tmp | perl -0777 -pe 's/\<[^\>]+\>//gs;s/body.*\}//s;s/&nbsp\;/ /gs'|sed  -n '/^ID[A-Z]*[0-9]/,/^THE NEXT.*on/p' > $temp/$ACTIVE
# ou
	cat $temp/$ACTIVE.tmp | perl -0777 -pe 's/\<[^\>]+\>//gs;s/body.*\}//s;s/&nbsp\;/ /gs'|sed  -n '/^ID[A-Z]*[0-9]/,/^Copyright.*$/p' > $temp/$ACTIVE

}
MIAMI(){
wget -q http://www.nhc.noaa.gov/text/refresh/MIATCPAT1+shtml/[0-9].shtml -O HTML.shtml
cat HTML.shtml|sed -n '/^BULLETIN/,/DISCUSSION/p' > $temp/$ACTIVE.tmp
cat $temp/$ACTIVE.tmp|sed -n 's/MB/HPA/;s/\([0-9]*[0-9] M.*\..*\.\)/ /g;s/\.\.\./ /g;p' > $temp/$ACTIVE
http://www.ssd.noaa.gov/goes/east/watl/vis-l.jpg #visible
http://www.ssd.noaa.gov/goes/east/watl/avn-l.jpg #infra avn (colored)
http://www.ssd.noaa.gov/goes/east/watl/rgb-l.jpg #infra rgb
http://cimss.ssec.wisc.edu/tropic2/real-time/atlantic/images/xxirng8.GIF # ir global
http://www.ssd.noaa.gov/goes/east/watl/ir2-l.jpg #ir blue
}
GLOBAL(){
	http://severe.worldweather.org/tc/swi/pop-ups/tc/lr_30201103203.meta
}
REUNION(){
	wget -q http://www.meteo.fr/temps/domtom/La_Reunion/TGPR/actif/activite_en_cours.html -O $temp/$ACTIVE.tmp
	cat $temp/$ACTIVE.tmp | perl -0777 -pe 's/\<[^\>]+\>//gs;s/body.*\}//s;s/&nbsp\;/ /gs'|sed -n '/[\U\|\L]/p'|sed -n '/^VOICI/,/*$/d;p' > $temp/$ACTIVE

}
#variable
REUNION_TAGS
## MAIN FUNCTION SUBFUNCTIONS
XMsg1(){
	#if [ -f /usr/bin/Xdialog ]&&[ -f /tmp/.X0-lock ]; then
	#	Xdialog --stdout --begin 0 0 --title "$0" --infobox "$(cat $temp/.MSG.txt)" 0 0 0
	#fi
	if [ -f /usr/bin/zenity ]&&[ -f /tmp/.X0-lock ]; then
		if [[ $(ps -A | grep "$TRAY.pl") == '' ]]||[[ $(ps -A | grep "$GUI.pl") == '' ]]; then
			msgtext=$(cat $temp/.MSG1.txt)
			zenity --info --no-wrap --text "\n$msgtext\n" --timeout=8 --title=$0 #\n$(echo $0|sed -n 's/.*\///p') message :\n\n
		fi
	fi
}
XMsg2(){
	#if [ -f /usr/bin/Xdialog ]&&[ -f /tmp/.X0-lock ]; then
	#	Xdialog --stdout --begin 0 0 --title "$0" --infobox "$(cat $temp/.MSG.txt)" 0 0 0
	#fi
	if [ -f /usr/bin/zenity ]&&[ -f /tmp/.X0-lock ]; then
		if [[ $(ps -A | grep "$TRAY.pl") == '' ]]||[[ $(ps -A | grep "$GUI.pl") == '' ]]; then
			msgtext=$(cat $temp/.MSG2.txt)
			zenity --question --no-wrap --text "\n$msgtext\n\n$INTERFACE" --timeout=20 --title=$0 #\n$(echo $0|sed -n 's/.*\///p') message :\n\n
			if [ "$?" == "0" ];then
				$0.pl
			fi
		fi
	fi
}
connection_control(){
	PING=$(ping -q -c 1 nvidia.com | sed -n '4p' | awk '{print $1}')
}
tracker(){
	if [ -f $temp/$TR1 ] ; then
		ACTIVE=$TR2
	else
		ACTIVE=$TR1
	fi
	if [[ $PING == 1 ]];then
		REUNION
	else
		echo -e "$CONNECTION" > $temp/.MSG1.txt
		XMsg1
		exit 0
	fi
	chmod 666 $temp/$ACTIVE.tmp
	rm -f $temp/$ACTIVE.tmp
}
remove(){
if [ -f $temp/$TR1 ] ; then
		chmod 666 $temp/$TR1
		TR1_INDATE=$( cat $temp/$TR1 | grep "$query0" | cut -d ' ' -f3,6|sed -n 's/H//;s/ //p' )
		TR1_DAY=$( ls -l $temp/$TR1 | awk '{ print $6 }' | sed -n 's/-//g;p' )
		TR1_TIME=$( ls -l $temp/$TR1 | awk '{ print $7 }' | sed -n 's/://p' )
	if [ -f $temp/$TR2 ] ; then
		chmod 666 $temp/$TR2
		TR2_INDATE=$( cat $temp/$TR2 | grep "$query0" | cut -d ' ' -f3,6|sed -n 's/H//;s/ //p')
		TR2_DAY=$( ls -l $temp/$TR2 | awk '{ print $6 }' | sed -n 's/-//g;p' )
		TR2_TIME=$( ls -l $temp/$TR2 | awk '{ print $7 }' | sed -n 's/://p' )
		if [[ $(echo $TR2_INDATE| grep "[0-9]") != '' ]] ; then
			if [[ $TR1_INDATE == $TR2_INDATE ]]; then
				echo -e "\f$v  $BULLETIN_CHECK\f$t"
				echo "$BULLETIN_CHECK" > $temp/.MSG1.txt
				rm -f $temp/$TR2
				XMsg1
				exit 0
			else
				rm -f $temp/$TR1
				mv -f $temp/$TR2 $temp/$TR1
				echo -e " $v\f $ACTIVITY1\n"
				echo "$ACTIVITY1" > $temp/.MSG1.txt
				#XMsg2
			fi
		else
			echo -e "$v\f  $ACTIVITY2\f$t"
			echo "$ACTIVITY2" > $temp/.MSG1.txt
			XMsg1
			if [ "$arg" == "c" ] ; then
				cron_noactivity
				exit 0
			else
				exit 0
			fi
		fi
	else
		if [[ $(echo $TR1_INDATE| grep "[0-9]") == '' ]]; then
			echo -e "$v\f  $ACTIVITY3\f$t"
			echo "$ACTIVITY3" > $temp/.MSG1.txt
			XMsg1
			if [ "$arg" == "c" ] ; then
				cron_noactivity
				exit 0
			else
				exit 0
			fi
		else
			if [ -f $temp/$TR2 ]; then
				rm -f $temp/$TR1
				mv -f $temp/$TR2 $temp/$TR1
			fi
			echo -e "$v\f  $ACTIVITY1\f$t"
			echo "$ACTIVITY1" > $temp/.MSG1.txt
			#XMsg2
		fi
	fi
fi
}
## cron functions
cron_var(){
	cron_file=$( $timer -l | awk '{ print $'$PRT2' }' | cut -d ',' -f 1 )
	conf_file=$( echo "$CRON" | awk '{ print $'$PRT2' }' )
}
cron_line(){
	if [ "$argX" == "x" ] ; then
		opt="-x"
	else
		opt=""
	fi
	echo "$CRON $0 -c $opt" >> $temp/.cron$USER
	$timer $temp/.cron$USER
	rm -f $temp/.cron$USER
}
cron_noactivity(){
	CRON="$preopts 01 23"$sep"11 * * *"
	if [ "$( $timer -l )" == '' ] ; then
		argX=""
		cron_line
	else
		cron_var
		if [ "$cron_file" != "$conf_file" ] ; then
			argX=""
			$timer -r ; cron_line
		fi
	fi
}
cron_activity(){
	CRON="$preopts 01 5"$sep"11"$sep"17"$sep"23 * * *"
	cron_var
	if [ "$cron_file" != "$conf_file" ] ; then
		$timer -r ; cron_line
	fi
}
cron_alert(){
	CRON="$preopts 01 2"$sep"5"$sep"8"$sep"11"$sep"14"$sep"17"$sep"20"$sep"23 * * *"
	cron_var
	if [ "$cron_file" != "$conf_file" ] ; then
		$timer -r ; cron_line
	fi
}
cron_image(){
	if [ "$( $timer -l )" != '' ] ; then
		if [ "$( $timer -l | sed -n 1p | grep -w 'i')" == '' ]; then
			$timer -l | sed -n 1p > $temp/.cron$USER
		fi
	fi
	iCRON="$preopts */60 * * * *"
	echo "$iCRON $0 -i" >> $temp/.cron$USER
	$timer $temp/.cron$USER
	rm -f $temp/.cron$USER
}
cron_image_daily(){
	if [ "$( $timer -l )" != '' ] ; then
		if [ "$( $timer -l | sed -n 1p | grep -w 'i')" == '' ]; then
			$timer -l | sed -n 1p > $temp/.cron$USER
		fi
	fi
	iCRON="$preopts 01 14"$sep"23 * * *"
	echo "$iCRON $0 -i" >> $temp/.cron$USER
	$timer $temp/.cron$USER
	rm -f $temp/.cron$USER
}
cron_season(){
	iCRON="$preopts * * * 9 *"
	echo "$iCRON $0 -i -c" >> $temp/.cron$USER
	$timer $temp/.cron$USER
	rm -f $temp/.cron$USER
}
cron_check(){
	if [ "$( $timer -l )" == '' ] ; then
		echo -e "\n$v  $CR_DAILY_CK\f $t"
		echo "$CR_DAILY_CK" > $temp/.MSG.txt
	else
		if [[ $( $timer -l | sed -n 1p | awk '{ print $'$PRT8'}' ) != '' ]] ; then
			fond="."
		else
			fond="\n  $CR_BG_CK"
		fi
		if [[ $( $timer -l | sed -n 2p ) != '' ]] ; then
			count=$( $timer -l | awk '{ print $(echo $'$PRT2') }' | sed -n 1p | sed -n "s/'$sep'/h00'$sep' /g;s/$/h00/p" )
			class_type="$CR_BULL"
			affect="$CR_DO"
			if [[ $( $timer -l | grep -w 'i' | awk '{print $'$PRT2')}') == "*" ]] ; then
				tranche="$CR_HOUR"
			else
				tranche="$CR_DAY"
			fi
			icount="\n  $CR_DAILY_CK $tranche."
		else
			if [[ $( $timer -l | grep -w 'i') != '' ]] ; then
				class_type="$CR_SAT"
				activity_info=" $CR_SAT_NO_CK"

			fi
			if [[ $( $timer -l | awk '{ print $'$PRT2' }' | sed -n 1p) == "*" ]] ; then
				count=$( $timer -l | awk '{ print $(echo $'$PRT1') }' | sed -n 1p | sed -n 's/*\///g;s/$/mn/p' )
				affect="$CR_SAT_EACH_S"
			else
				count=$( $timer -l | awk '{ print $'$PRT2' }' | sed -n 1p | sed -n "s/'$sep'/h00'$sep' /g;s/$/h00/p" )
				affect="$CR_SAT_EACH"
			fi
			icount="\n  $CR_SAT_NO"
		fi
		echo -e "\n$v  $CR_CK $class_type $affect $count$v $fond$icount$activity_info\n $t"
		echo -e "$CR_CK $class_type $affect $count$fond$icount$activity_info"|sed -n 's/^  //g;p' > $temp/.MSG.txt
		#msg
	fi
}
# satellite image donwloader
image(){
	image_view(){
	if [ "$argI" == "true" ] ; then
		if [ "$(ls -l $DIR/$current_path)" != '' ] ; then
			$viewer $sat_path/$(date +%m%d-%H%M).jpg
		fi
	fi
	}
	actual=$( date +%Y%m%d%H%M)
	if [ -f $log ];then
		previous=$( cat $log | sed -n '$p'|cut -d ',' -f4 )
	else
		previous=0
	fi
	if [ "$[$actual-$previous]" -ge "10000" ] ; then
		current_path="daily_sat"
		mkdir -p $DIR/$current_path
		sat_path=$(date +%y-%m)
	else
			current_path=$(cat $log|sed -n '$p'|cut -d ',' -f5)
			sat_path="sat"
	fi
	chmod 755 $DIR/$current_path
	cd $DIR/$current_path
	if [[ $(ls -d $DIR/$current_path/$sat_path 2>/dev/null) == '' ]] ; then
		mkdir -p $sat_path ; chmod 755 $sat_path
	fi
	wget -q http://www.meteo.fr/temps/domtom/La_Reunion/TGPR/saison/images/satellite/DerImageSatellite.jpg -O $sat_path/$(date +%m%d-%H%M).jpg
	echo -e "$(date +%y%m%d%H),$DIR/$current_path/$sat_path/$(date +%m%d-%H%M).jpg" >> $DIR/.image.log
	if [[ $argI == true ]];then
		image_view
	fi
	cd $temp
}
archive_year(){
	echo
}
archive_file(){
	if [[ "$( date +%m )" -gt "04" ]] ; then
		mkdir -p $DIR/archive
		cd $DIR
		DIR_T=$(echo $DIR | sed -n 's/\//\\\//g;s/$/\\\//p')
		TAR_LIST=$(ls -ld $DIR/[[:upper:]]* | sed -n "s/"$(echo $DIR_T)"//p" | awk '{ print $8 }')
		if [ "$TAR_LIST" != '' ] ; then
			for tar_file in $TAR_LIST ; do
				tar acf ./archive/$tar_file.tar.gz $tar_file
				cp -f ./archive/$tar_file.tar.gz ./archive/$YDir
				#rm -r $DIR/$tar_file
			done
		fi
	fi
}
archive_season(){
	if [[ "$( date +%m )" -ge "05" ]] ; then
		YDir=$(date +Y%)-$($(date +%Y) - 1)
		mkdir -p $DIR/archive/$YDir
		archive_year
		cron_season
	fi
}
#KML
pre_report(){
	prefix_date=$(date +%d)
	report_time=$(echo $txt0|cut -d ' ' -f6)
	longi=$(echo $lon | sed -n 's/$/00000/p')
	lati=$(echo $lat | sed -n 's/$/00000/p')
	if [[ $prefix_date != $(cat $temp/$TR1 | grep "$query0" | cut -d ' ' -f3|sed -n 's/ //g;p') ]];then
		report_date=$(cat $temp/$TR1 | grep "$query0" | cut -d ' ' -f3|sed -n 's/ //g;p')/$(date +%m)
		log_date=$(date +%m)$(cat $temp/$TR1 | grep "$query0" | cut -d ' ' -f3|sed -n 's/ //g;p')
	else
		report_date=$(date +%d/%m)
		log_date=$(date +%m%d)
	fi
}
kml_pre(){
# color violet=709c00ff rouge=700024ff orange=700089ff jaune=7000d8ff vert=7000ff9a
# bleu=70ff0008 bleuclair=70ff8f00 cyan=70ddff00 kaki=70067413 rose=70e546ff
	kml_file=$DIR/$CURRENT/$CURRENT.kml
	kmltmp=$DIR/$CURRENT/.tmpkml
	current_log=$DIR/$CURRENT/$CURRENT.txt
	#report_name="$ex"$(cat $tempf|sed -n '1p')
	report_name="$ex"$(cat $log|sed -n '$p'|cut -d ',' -f5)
	if [[ $(cat $current_log|sed -n '$p'|cut -d ',' -f12) != '' ]];then
		report_ID=$(cat $current_log|sed -n '$p'|cut -d ',' -f12)
	else
		report_ID=$report_name
	fi
	if [ -f $log ];then
		if [[ $(cat $log|sed -n '$p'|grep -o "$CURRENT") != '' ]];then
			last_lon=$(cat $log | sed -n '/'$CURRENT'/{x;$p}'|cut -d ',' -f7|sed -n 's/$/00000/p')
			last_lat=$(cat $log | sed -n '/'$CURRENT'/{x;$p}'|cut -d ',' -f6|sed -n 's/$/00000/p')

		else
			last_lon=$(cat $log|sed -n '$p'|cut -d ',' -f7|sed -n 's/$/00000/p')
			last_lat=$(cat $log|sed -n '$p'|cut -d ',' -f6|sed -n 's/$/00000/p')
		fi
	else
		last_lon=$longi
		last_lat=$lati
	fi
	pressure=$(echo "$txt2"|awk '{print $1}')
	speed=$(echo $txt5|awk '{print $3}')
	direction=$(echo $txt5|awk '{print $1}')
	distance=$(echo $txt4|awk '{print $1}')
	color_list_type="ZONE,fade,80aeaeae|PERTURBATION,cyan,80ddff00|DEPRESSION,bleuclair,70ff8f00|MODEREE,bleu,70ff0008|TERRE,kaki,70067413|EXTRA,rose,70e546ff|\
	FORTE,vert,7000ff9a|CYCLONE,jaune,7000d8ff|INTENSE,orange,700089ff|TRES.*INTENSE,rouge,700024ff|TRES.*TRES.*INTENSE,violet,709c00ff"
	if [ -f $kml_file ];then
		report_tag=$report_date
	else
		report_tag=$report_name
	fi
	if [[ $(echo $txt1|grep "$report_name") != '' ]];then
		report_class=$(echo $txt1|sed -n "s/$report_name//p")
	else
		report_class=$(echo $txt1)
	fi
}
coloring(){
for colors_list in $(echo -e "$color_list_type"|tr '|' '\n'); do
	color_key=$(echo "$colors_list" |cut -d ',' -f1)
	if [[ $(echo $txt1|grep -o "$color_key") != '' ]];then
	colortype=$(echo $colors_list|cut -d ',' -f2)
	color=$(echo $colors_list|cut -d ',' -f3)
	fi
done
}
kml(){
	track_icons(){
	icon_style="point"
	icon_style="shapes/shaded_dot.png"
	echo -e "    <Style id=\"$icon_style\">\n        <IconStyle>\n            <scale>1,4</scale>" > $kmltmp
	echo -e "                <Icon>\n                    <href>http://maps.google.com/mapfiles/kml/$icon_uri</href>" > $kmltmp
	echo -e "                </Icon>\n                <hotSpot x=\"22\" y=\"1\" xunits=\"pixels\" yunits=\"pixels\"/>" > $kmltmp
	echo -e "        </IconStyle>\n        <ListStyle>\n        </ListStyle>\n    </Style>" > $kmltmp
	echo -e "    <StyleMap id=\"m_$icon_style\">\n        <Pair>\n            <key>normal</key>" > $kmltmp
	echo -e "            <styleUrl>#$icon_style\</styleUrl>\n        </Pair>\n        <Pair>\n            <key>highlight</key>" > $kmltmp
	echo -e "            <styleUrl>#$icon_style\</styleUrl>\n        </Pair>\n   </StyleMap>" > $kmltmp
	}
	heading(){
	echo -e "<?xml version='1.0' encoding='UTF-8'?>" > $kmltmp
	echo -e "<kml xmlns=\"http://earth.google.com/kml/2.1\"" >> $kmltmp
	echo -e "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" >> $kmltmp
	echo -e "  <Document>\n    <Snippet/>\n    <Style id=\"$track\">\n        <IconStyle/>\n    </Style>" >> $kmltmp
	}
	linestyle(){
		echo -e "    <Style id=\"$colortype\">\n          <LineStyle>" >> $kmltmp
		echo -e "            <color>$color</color>\n            <width>4</width>" >> $kmltmp
		echo -e "          </LineStyle>\n    </Style>\n    <Folder>" >> $kmltmp
	}
	first_mark(){
	echo -e "      <Placemark>\n      <name>$report_time</name>" >> $kmltmp
	#echo -e "        <styleUrl>#$icon</styleUrl>" >> $kmltmp
	echo -e "        <Point>\n          <coordinates>$longi,$lati,0.000000</coordinates>\n        </Point>\n      </Placemark>" >> $kmltmp
	}
	report_mark(){
	echo -e "      <Placemark>\n        <name>$report_tag</name>\n        <Snippet/>" >> $kmltmp
	}
	second_mark(){
	echo -e "        <description><![CDATA[\n          <table>" >> $kmltmp
	echo -e "            <tr><td>ID: $report_ID </td></tr>" >> $kmltmp
	echo -e "            <tr><td>nom: $report_name </td></tr>" >> $kmltmp
	echo -e "            <tr><td>Type: $report_class </td></tr>" >> $kmltmp
	echo -e "            <tr><td>Pression: $pressure HPA </td></tr>" >> $kmltmp
	echo -e "            <tr><td>Longitude: $(echo $longi|sed -n 's/00000//p') </td></tr>" >> $kmltmp
	echo -e "            <tr><td>Latitude: $(echo $lati|sed -n 's/00000//p') </td></tr>" >> $kmltmp
	echo -e "            <tr><td>Vitesse: $speed KM/H </td></tr>\n            <tr><td>Déplacement: $direction </td></tr>" >> $kmltmp
	echo -e "            <tr><td>Distance des côtes: $distance KM </td></tr>\n          </table>\n        ]]></description>" >> $kmltmp
	echo -e "        <LookAt>\n          <longitude>$longi</longitude>\n          <latitude>$lati</latitude>" >> $kmltmp
	echo -e "          <tilt>0</tilt>\n        </LookAt>\n        <TimeStamp><when>$utc_time </when></TimeStamp>" >> $kmltmp
	echo -e "        <styleUrl>#$track</styleUrl>" >> $kmltmp
	echo -e "        <Point>\n          <coordinates>$longi,$lati,0.000000</coordinates>\n        </Point>" >> $kmltmp
	echo -e "      </Placemark>\n      <Placemark>\n        <styleUrl>#$colortype</styleUrl>" >> $kmltmp
	echo -e "        <LineString>\n        <tessellate>1</tessellate>\n        <coordinates>" >> $kmltmp
	if [ -f $kml_file ];then
		echo -e "          $last_lon,$last_lat,0.000000" >> $kmltmp
	else
		echo -e "          $longi,$lati,0.000000" >> $kmltmp
	fi
	echo -e "          $longi,$lati,0.000000" >> $kmltmp
	echo -e "        </coordinates>\n        </LineString>\n      </Placemark>" >> $kmltmp
	}
	bottom(){
	echo -e "    </Folder>\n  </Document>\n</kml>" >> $kmltmp
	}
	new_point(){
		coloring ; heading
		if [[ $(cat $kmltmp | grep -o -w "$colortype") == '' ]];then
			linestyle
		fi
		first_mark ; report_mark ; second_mark ; bottom
		cat $kmltmp > $kml_file
	}
	next_point(){
		coloring
		cat $kml_file | sed -n '/<\/Folder>/,/.*$\n/d;p' > $kmltmp
		cat $kmltmp > $kml_file
		if [[ $(cat $kmltmp | grep -o -w "$colortype") == '' ]];then
			lines="<Style id=\"$colortype\">\n          <LineStyle>\
\n            <color>$color<\/color>\n            <width>4<\/width>\
\n          <\/LineStyle>\n    <\/Style>\n    <Folder>"
			cat $kml_file|sed -n "s/<Folder>/$lines/i;p" > $kmltmp
		fi
		if [ -f $current_log ];then
		date_query=$(cat $current_log | sed -n '/'$prefix_date'/{x;$p}'|cut -d ',' -f1)
		date_current=$(cat $current_log | sed -n '/'$prefix_date'/{$p}'|cut -d ',' -f1)
		#time_query=$(cat $current_log | sed -n '/'$prefix_date'/{x;$p}'|cut -d ',' -f2)
			#if [[ $(cat $current_log|sed -n '$p'|cut -d ',' -f1|grep -o "$date_query") != '' ]]; then
			if [[ $date_query -eq $date_current ]]; then
				report_tag=$report_time
			else
				report_tag=$report_date
				first_mark
			fi
			if [[ $(cat $current_log|sed -n '$p'|grep -o "$report_name") == '' ]]; then
				report_tag=$report_name
				first_mark
			fi
		fi
		report_mark
		second_mark
		bottom
		cat $kmltmp > $kml_file
	}
	echo "" > $kmltmp
	if [ -f $kml_file ]; then
		next_point
	else
		new_point
	fi
	mkdir -p $DIR/kml
	cp -f $kml_file $DIR/kml
}
##MAIN FUNCTION
TRACK(){
# creation de base du ficheir gpx
point_start(){
	echo -e "<?xml version='1.0' encoding='UTF-8'?>" >> $gpx_file
	echo -e "<gpx version=\"1.1\" creator=\"h_tracker\" xmlns=\"$(uname -n) $(uname -o)\"" >> $gpx_file
	echo -e "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" >> $gpx_file
	echo -e "    xsi:schemaLocation=\"$(uname -n) $(uname -o) $DIR/$CURRENT\">\n  <metadata>" >> $gpx_file
	echo -e "    <bounds minlat=\"$lat\" minlon=\"$lon\" maxlat=\"$lat\" maxlon=\"$lon\" />\n  </metadata>" >> $gpx_file
	echo -e "  <trk>\n    <trkseg>" >> $gpx_file
	echo -e "      <trkpt lat=\"$lat\" lon=\"$lon\">\n        <time>$utc_time</time>\n      </trkpt>" >> $gpx_file
	echo -e "    </trkseg>\n  </trk>\n</gpx>" >> $gpx_file
}
# nouveau point gpx
point_new(){
	gpxtmp=$DIR/$CURRENT/.gpx
	cat $gpx_file | perl -n -pe  "s/\<\/trkseg\>/  \<trkpt lat=\"$lat\" lon=\"$lon\"\>\n        \<time\>$utc_time\<\/time\>\n      \<\/trkpt>\n    \<\/trkseg\>/"|sed -n "s/minlat.*maxlat/minlat=\"$lat\" minlon=\"$lon\" maxlat/i;p" > $gpxtmp
	cat $gpxtmp > $gpx_file
}
# genrate temp file
new_tempf(){
	adv_date=$(echo $txt0|awk '{ print $3$6 }'|sed -n 's/H//p')
	if [ -f $log ];then
		if [[ $(echo $txt1|grep -o "$CURRENT") == '' ]]; then
			CURRENT=$(cat $log | sed -n '$p'|cut -d ',' -f5)
		fi
		echo -e "$CURRENT\n$adv_date\n$(date +%Y%m)$adv_date\n$lon $lat" > $tempf
		echo -e "$log_date,$(echo $txt0|awk '{ print $6 }'|sed -n 's/H//p'),$adv_date,$(date +%Y%m)$adv_date,$CURRENT,$lat,$lon,$utc_time" >> $log
	fi
}
# migration sur changement de dénomination ou nom
migrate(){
if [ -f $log ];then
		actualy=$(cat $log | sed -n '$p')
		previously1=$(cat $log | sed -n '/'$CURRENT'/{g;1!p};h'|sed -n '$p')
		previously2=$(cat $log | sed -n '/'$CURRENT'/{g;$p};h')
		if [[ $(echo $actualy|cut -d ',' -f5) != $(echo $previously1|cut -d ',' -f5) ]];then
			if [[ $(echo $actualy|cut -d ',' -f5|grep "[A-Z]") != '' ]]&&[[ $(echo $previously1|cut -d ',' -f5|grep "[0-9]-[0-9]") != '' ]];then
				if [[ $(echo $actualy|cut -d ',' -f5|grep -o "[0-9]-[0-9]") == $(cat $DIR/$CURRENT/$CURRENT.txt|cut -d ',' -f12|grep -o "[0-9]-[0-9]") ]];then
					if [[ $(echo $actualy|cut -d ',' -f3) != $(echo $previously1|cut -d ',' -f3) ]];then
						diffdate=$[ $(echo $actualy|cut -d ',' -f3) - $(echo $previously1|cut -d ',' -f3) ]
						echo "$diffdate"
						if [[ $diffdate == 600||300 ]] ; then
							if [[ $( echo $txt1 | grep -o "EX[- ]") != '' ]] ; then
								OLDG=$(echo $actualy|cut -d ',' -f5)
								NEWG=$(echo $previously1|cut -d ',' -f5)
							else
								OLDG=$(echo $previously1|cut -d ',' -f5)
								NEWG=$(echo $actualy|cut -d ',' -f5)
							fi
							cat $DIR/$OLDG/$OLDG.gpx|sed -n "s/$OLDG/$NEWG/i;p" > $DIR/$NEWG/$NEWG.gpx
							cat $DIR/$OLDG/$OLDG.kml > $DIR/$NEWG/$NEWG.kml
							cat $DIR/$OLDG/$OLDG.txt > $DIR/$NEWG/$NEWG.txt
							cp -f $DIR/$OLDG/*.txt $DIR/$NEWG
							cp -R -f $DIR/$OLDG/sat/ $DIR/$NEWG
							point_new
							cd $DIR
							rm -f -R $OLDG
							cd /home/$USER
						fi
					fi
				fi
			fi
		fi

fi
}
nome(){
#ifs=$IFS
#IFS="
#"
	CURRENT_TMP=$(echo "$txt1"| awk '{print $NF}')
	if [[ $(echo $CURRENT_TMP|grep "EX[- ]") != '' ]]; then
		CURRENT=$(echo $CURRENT_TMP|sed -n 's/EX[- ]//p')
		ex="EX-"
	elif [[ $(echo $CURRENT_TMP|grep -o "TROPICALE\|TROPICAL") != '' ]];then
		CURRENT=$(cat $stormlog|sed -n '{x;$p}'|cut -d ',' -f4)
	else
		CURRENT=$CURRENT_TMP
	fi
#IFS=$ifs
}
# load message vars
	messages
# download
	connection_control
	tracker
# compare old cache file with new and remove old if necessary
	remove
# universal time
utc_time=$( date +%Y-%m-%dT\ %H:%m:00Z)
# bulletin date
txt0=$( cat $temp/$TR1 | grep "$query0"|sed -n 's/://p')
#nature
typeZ="ZONE,PERTURBATION,TROPICALE,CYCLONE,EXTRA,COMBLANT,TERRE"
for system in $(echo "$typeZ"|tr ',' '\n');do
	if [[ $(cat $temp/$TR1 | grep -o "$system") != '' ]];then
		txt1=$(cat $temp/$TR1| grep "$system")
	fi
done
##pression
	txt2=$( cat $temp/$TR1 | grep -w "$query1" | cut -d':' -f2|sed -n 's/ * //p')
##position
	txt3=$( cat $temp/$TR1 | grep -w "$query2" | cut -d':' -f2|sed -n 's/ * //p')
##distance
	txt4=$( cat $temp/$TR1 | grep -w "$query3" | cut -d':' -f2|sed -n 's/ * //p')
##deplacement
	txt5=$( cat $temp/$TR1 | grep -w "$query4" | cut -d':' -f2|sed -n 's/ * //p')
## détection des alertes
#if [[ $(cat $temp/.MSG2.txt | grep -o "$system") != '' ]] ; then
from=$[ $(cat -n $temp/$TR1 | grep "$query9"|awk '{print $1}') +1 ]
to=$[ $(cat -n $temp/$TR1 | grep "$query10"|awk '{print $1}') -1 ]
if [[ $(cat $temp/$TR1 | sed -n ''$from','$to'p' | grep -o "PAS\|NO" ) != '' ]];then
	alert="$NO_ALERT"
	if [ "$arg" == "c" ] ; then
		cron_activity
	fi
else
	alert=$( cat $temp/$TR1 | sed -n ''$from','$to'p')
	if [ "$arg" == "c" ] ; then
		cron_alert
	fi
fi
#fi
##display
echo -e "\f$v  $txt0\n  $y$txt1\n  $j$txt2\n  $txt3\n  $txt4\n  $txt5\n\f  $v$alert \n $t"
lon=$( echo $txt3|awk '{print $5$4}'|sed -n 's/OUEST/\-/p;s/EST//p' )
lat=$( echo $txt3|awk '{print $2$1}'|sed -n 's/NORD//p;s/SUD/\-/p' )
## current storm folder creation
nome
pre_report
new_tempf
mkdir -p $DIR/$CURRENT #; echo -e "$j$CURRENT ** "
## current storm new point file creation & display
txt_file=$DIR/$CURRENT/$( date +%y%m%d%H ).txt
echo -e "$txt0\n$txt1\n$txt2\n$txt3\n$txt4\n$txt5" > $txt_file
gpx_file="$DIR/$CURRENT/$CURRENT.gpx"
echo -e "$ACTIVITY1\n$(cat $txt_file)\n$alert" > $temp/.MSG2.txt
if [ "$(cat -n $temp/.MSG2.txt| awk '{print $1}'|sed -n '$p')" -ge 5 ]; then
	if [[ $( ls $gpx_file 2>/dev/null ) == '' ]] ; then
		point_start
		migrate
	else
		point_new
	fi
	kml_pre
	coloring
	kml
else
	echo -e "UNE ERREUR EST SURVENUE\nL'$ACTIVITY1\nN'A PAS ÉTÉ ENREGISTRÉE CORRECTEMENT." > $temp/.MSG2.txt
fi
if [ -f $current_log ];then
	storm_id=$(cat $current_log|sed -n '1p'|cut -d ',' -f3)
else
	storm_id=$report_name
fi

echo -e "$report_date,$report_time,$report_name,$report_class,$pressure,$distance,$direction,$speed,$lat,$lon,$utc_time,$storm_id" >> $current_log
XMsg2
}

## MAIN OPTIONS
while [ "$#" -gt 0 ] ; do
	if [ "$#" -ge 1 ] ; then
		if [ "$1" == '-k' ] || [ "$2" == '-k' ]; then
		ht=6 ; lg=60
		elif [ "$1" == '-c' ] ; then
		display=" -display :0"
		else
		ht=16 ; lg=40
		fi
		if [ "$1" == "-x" ]; then
			if [ "$2" == '' ] ; then
				echo -e "\n$y L'option$j -x$y ne peut pas s'exécuter seule.$t\n" ; exit 1
			else
				echo -e "\n$y Placer l'option$j -x$y en seconde position.$t\n" ; exit 1
			fi
		fi
	fi
	termx='xterm'$display' -hold -sb -bg black -bd black -bw 0 -geometry '$lg'x'$ht' -e '$0''
	messages
	case "$1" in
		-k|--check)
				if [ "$#" -ge "2" ] ; then
					if [ "$1" != "-x" ] | [ "$2" != "-x" ]; then
						$0 CC ; shift 1
					else
						$termx CCX ; shift 2
					fi
				else
					$0 CC ; exit 0
				fi
		;;
		-p|--pontually)
				if [ "$#" -ge "2" ] ; then
					if [ "$1" != "-x" ] | [ "$2" != "-x" ]; then
						$0 T ; shift 1
					else
						$termx TX ; shift 2
					fi
				else
					$0 T ; exit 0
				fi
		;;
		-c|--cron)
			rm -f $temp/.cron$USER
				if [ "$#" == "2" ] ; then
					if [ "$1" != "-x" ] | [ "$2" != "-x" ]; then
						$0 C ; shift 1
					else
						$termx CX ; shift 2
					fi
				else
					$0 C ; exit 0
				fi
		;;
		-s|--stop)
			crontab -r ; rm -f $temp/.cron$USER ; exit 0
		;;
		-r|--reset)
			rm -f $temp/$TR1 ; rm -f $temp/$TR2 ; exit 0
		;;
		-i|--image)
			if [ "$#" -ge "2" ] ; then
					if [ "$1" != "-x" ] | [ "$2" != "-x" ]; then
						$0 I ; shift 1
					else
						$0 I ; shift 2
					fi
				else
					$0 I ; exit 0
			fi
		;;
		-hi|--hourly-image)
			$0 IC ; exit 0
		;;
		-di|--daily-image)
			$0 ID ; exit 0
		;;
		-iw|--image-wiever)
			if [ "$#" -ge "2" ] ; then
					if [ "$1" != "-x" ] | [ "$2" != "-x" ]; then
						$0 IW ; shift 1
					else
						$0 IW ; shift 2
					fi
				else
					$0 IW ; exit 0
			fi
		;;
		''|-h|--help)
			echo -e "\nusage : $(basename $0) (opt1) (opt2) (opt3)"
			echo -e "\n L'option$j x$t doit être placée obligatoirement après$j -p, -k, -c$t\n dont elle dépends."
			echo -e "\t -p, --ponctually \t one shot without cron check."
			echo -e "\t -c, --cronly \t\t with cron automate support."
			echo -e "\t -s, --stop \t\t stop script automation \n\t\t\t\t and remove all crontab user file. "
			echo -e "\t -k, --check \t\t check cron config."
			echo -e "\t -r, --reset \t\t reset html file ( in case of dl mistake)."
			echo -e "\t -i, --image \t\t dowload ponctually satellite image"
			echo -e "\t -di, --daily-image \t check daily satellite image"
			echo -e "\t -hi, --hourly-image \t check hourly satellite image."
			if [ -x /usr/bin/eog ] ; then
				echo -e "\t -iw, --image-viewer \t display satellite image "
			fi
			echo -e "\t -x, --xterm \t\t xterm pseudo graphic ui."
			echo -e "\n\t -h, --help \t\t this help."
			echo -e "\n\t -e, --exemple \t\t commande line exemples."
			shift
		;;
		-e)
			echo -e "\n$r Important$t:\n Le répertoire par default est$j $DIR$t"
			echo -e " Modifiez la ligne$j 28$t du script pour diriger les données vers un autre dossier."
			echo -e "\n$r Rappel$t:\n L'option$j x$t ne peut être exécutée seule et doit être placée"
			echo -e " obligatoirement après$j -p, -k, -c$t dont elle dépends."
			echo -e "\n exemples:\n\t $j$(basename $0) -p -x -i\n\t $(basename $0) -i -p -x$t"
			echo -e " exécute le script ponctuellement en pseudo GUI Xterm avec téléchargement\n de l'image satellite."
			echo -e "\n autres exemples:\n\t $j$(basename $0) -p -i\n\t $(basename $0) -i -p$t"
			echo -e " exécute le script dans le terminal ponctuellement avec téléchargement\n de l'image satellite."
			echo -e "\n\t $j$(basename $0) -c -di\n\t $(basename $0) -c -hi$t"
			echo -e " exécute le script selon les règles cron respectivement avec téléchargement"
			echo -e " de l'image satellite journalier ou toutes les heures."
			echo -e " Et ainsi de suite ... \n"
			shift #; exit 1
		;;
		L)
			echo -e "-k\n-p\n-c\n-r\n-s\n-i\n-hi\n-di\n-iw\n-h\n-x"
			shift
		;;
		T )
			#echo -e "$y no cron"
			TRACK
			shift
		;;
		C)
			arg="c" ; rm -f $temp/.cron$USER
			#echo -e "$y cron"
			TRACK
			shift
		;;
		CC)
			#echo -e "$y check cron"
			cron_check
			shift
		;;
		TX)
			argX="x"
			#echo -e "$y no cron"
			TRACK
			shift
		;;
		CX)
			arg="c"
			argX="x"
			rm -f $temp/.cron$USER
			#echo -e "$y cron"
			TRACK
			shift
		;;
		CCX)
			argX="x"
			#echo -e "$y check cron"
			cron_check
			shift
		;;
		I)
			image
			shift
		;;
		IC)
			cron_image
			shift
		;;
		ID)
			cron_image_daily
			shift
		;;
		IW)
			argI='true'
			image
			shift
		;;
		tf)
			archive_file ; exit 0
		;;
		*)
			echo -e "\n Option$j $@$t inconnue, faites$j $(basename $0) -h$t ou$j --help$t pour"
			echo -e " obtenir la liste ou faite$j $(basename $0) -e$t pour obtenir des exemples.\n"
			shift
		;;
	esac
done
exit 0
